package com.fresh.liangyi.service.impl;

import com.fresh.liangyi.dao.UserMapper;
import com.fresh.liangyi.model.domain.Address;
import com.fresh.liangyi.model.domain.Authority;
import com.fresh.liangyi.model.domain.User;
import com.fresh.liangyi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@CacheConfig(cacheNames = "user")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public User selectUserWithId(Integer id) {
        log.info("作者id："+id);
        Object o=redisTemplate.opsForValue().get("user_"+id);
        if(o!=null){
            return (User)o;
        }else{
            User user=userMapper.selectUserWithId(id);
            if(user!=null){
                redisTemplate.opsForValue().set("user_"+id,user,1000, TimeUnit.SECONDS);
            }
            return user;
        }
    }

    @Override
    public User getByUserName(String username) {
        log.info("username:"+username);
        Object o=redisTemplate.opsForValue().get("user_"+username);
        if(o!=null){
            return (User)o;
        }else{
            User user=userMapper.getUserByName(username);
            log.info("user:"+user);
            if(user!=null){
                redisTemplate.opsForValue().set("user_"+username,user,1000, TimeUnit.SECONDS);
            }
            return user;
        }
    }

    @Override
    public List<Authority> getAuthority(String username) {
        return null;
    }

    @Override
    public List<Address> getAddressByUserId(Integer id) {
        return userMapper.getAddressByUserId(id);
    }

    @Override
    public Address getAddressById(Integer id) {
        return userMapper.getAddressById(id);
    }

    @Override
    public Integer addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public Integer addAuthorityByUser(Integer userId, Integer authorityId) {
        return userMapper.addAuthorityByUser(userId,authorityId);
    }
}
